<template>
    <div class="container">
        <div class="header">
            <h2>学院管理</h2>
            <el-button type="primary" @click="handleAdd">添加学院</el-button>
        </div>

        <el-table :data="departmentList" border style="width: 100%" v-loading="loading">
            <el-table-column prop="code" label="学院编号" width="120" />
            <el-table-column prop="name" label="学院名称" width="150" />
            <el-table-column label="操作" width="180" fixed="right">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row.code)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="学院名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入学院名称" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../api/request.js'

const departmentList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加学院')
const formRef = ref(null)

const form = reactive({
    code: null,
    name: ''
})

const rules = {
    name: [{ required: true, message: '请输入学院名称', trigger: 'blur' }]
}

onMounted(() => {
    fetchDepartments()
})

// 获取公寓列表
const fetchDepartments = async () => {
    loading.value = true
    try {
        const res = await api.department.getAll()
        if (res.code === 1) {
            departmentList.value = res.data
        } else {
            ElMessage.error(res.msg || '获取学院列表失败')
        }
    } catch (error) {
        console.error('获取学院列表出错:', error)
        ElMessage.error('获取学院列表失败')
    } finally {
        loading.value = false
    }
}

// 添加公寓
const handleAdd = () => {
    dialogTitle.value = '添加学院'
    form.code = null
    form.name = ''
    dialogVisible.value = true
}

// 编辑公寓
const handleEdit = (row) => {
    dialogTitle.value = '编辑学院'
    Object.assign(form, row)
    dialogVisible.value = true
}

// 删除学院
const handleDelete = (code) => {
    ElMessageBox.confirm('确定要删除该学院吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await api.department.delete(code)
            if (res.code === 1) {
                ElMessage.success('删除成功')
                fetchDepartments()
            } else {
                ElMessage.error(res.msg || '删除失败')
            }
        } catch (error) {
            console.error('删除学院出错:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => { })
}

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return

    formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                let res
                if (form.code) {
                    res = await api.department.update(form)
                } else {
                    res = await api.department.add(form)
                }

                if (res.code === 1) {
                    ElMessage.success(form.code ? '更新成功' : '添加成功')
                    dialogVisible.value = false
                    fetchDepartments()
                } else {
                    ElMessage.error(res.msg || (form.code ? '更新失败' : '添加失败'))
                }
            } catch (error) {
                console.error(form.code ? '更新学院出错:' : '添加学院出错:', error)
                ElMessage.error(form.code ? '更新失败' : '添加失败')
            }
        }
    })
}
</script>

<style scoped>
.container {
    padding: 20px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
</style>